<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件分享</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: white;
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 800px;
            margin: 20px auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .batch-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.9;
        }

        .batch-actions-bar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #f8f9fa;
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #e1e5e9;
        }

        .btn-batch-download {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 10px 20px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-batch-download:hover {
            background: linear-gradient(135deg, #20c997 0%, #17a2b8 100%);
            transform: translateY(-1px);
        }

        .batch-hint {
            color: #666;
            font-size: 12px;
            font-style: italic;
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
            margin: 0;
        }

        .content {
            padding: 30px;
        }

        .file-list {
            list-style: none;
        }

        .file-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 20px;
            border: 1px solid #e1e5e9;
            border-radius: 12px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        .file-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
            background: white;
        }

        .file-info {
            display: flex;
            align-items: center;
            flex: 1;
            min-width: 0;
        }

        .file-preview {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            object-fit: cover;
            margin-right: 15px;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            flex-shrink: 0;
        }

        .file-details {
            flex: 1;
            min-width: 0;
        }

        .file-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
            word-break: break-all;
            font-size: 16px;
        }

        .file-size {
            color: #666;
            font-size: 12px;
        }

        .file-actions {
            display: flex;
            gap: 10px;
            flex-shrink: 0;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .btn-view {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            color: #1976d2;
        }

        .btn-view:hover {
            background: linear-gradient(135deg, #bbdefb 0%, #90caf9 100%);
            transform: translateY(-1px);
        }

        .btn-download {
            background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
            color: #2e7d32;
        }

        .btn-download:hover {
            background: linear-gradient(135deg, #c8e6c9 0%, #a5d6a7 100%);
            transform: translateY(-1px);
        }

        .error-container {
            text-align: center;
            padding: 60px 30px;
            color: #666;
        }

        .error-container h2 {
            color: #dc3545;
            margin-bottom: 20px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 30px;
            color: #666;
        }

        .empty-state-icon {
            font-size: 48px;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            .container {
                border-radius: 15px;
            }

            .header {
                padding: 20px;
            }

            .header h1 {
                font-size: 20px;
            }

            .content {
                padding: 20px;
            }

            .file-item {
                flex-direction: column;
                align-items: stretch;
                gap: 15px;
            }

            .file-info {
                flex-direction: column;
                text-align: center;
                gap: 10px;
            }

            .file-actions {
                justify-content: center;
            }

            .btn {
                flex: 1;
                justify-content: center;
                padding: 12px 20px;
                font-size: 14px;
            }
        }

        @media (max-width: 480px) {
            .file-actions {
                flex-direction: column;
            }

            .btn {
                width: 100%;
            }
        }

        /* 图片查看模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            max-width: 90%;
            max-height: 90%;
            position: relative;
        }

        .modal-image {
            max-width: 100%;
            max-height: 90vh;
            border-radius: 8px;
        }

        .modal-close {
            position: absolute;
            top: -40px;
            right: 0;
            color: white;
            font-size: 30px;
            cursor: pointer;
            background: none;
            border: none;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📁 文件分享</h1>
            <div th:if="${isBatch}" class="batch-info">
                <p>批量分享 - 共 <span th:text="${files != null ? files.size() : 0}"></span> 个文件</p>
            </div>
        </div>
        
        <div class="content">
            <div th:if="${error}">
                <div class="error-container">
                    <h2>❌ 链接已失效</h2>
                    <p th:text="${error}"></p>
                    <p>请联系分享者重新获取链接</p>
                </div>
            </div>
            
            <div th:if="${error == null and files == null}">
                <div class="empty-state">
                    <div class="empty-state-icon">📁</div>
                    <h2>暂无分享文件</h2>
                    <p>分享者还没有分享任何文件</p>
                </div>
            </div>
            
            <div th:if="${error == null and files != null}">
                <!-- 批量操作栏 -->
                <div th:if="${isBatch}" class="batch-actions-bar">
                    <button class="btn btn-batch-download" onclick="batchDownloadAll()">
                        📦 批量下载全部
                    </button>
                    <span class="batch-hint">提示：也可以单独下载每个文件</span>
                </div>
                
                <ul class="file-list">
                    <li th:each="file : ${files}" class="file-item">
                        <div class="file-info">
                            <div th:if="${file.image}" class="file-preview">
                                <img th:src="'/albums/' + ${file.fileName}" th:alt="${file.originalName}" style="width: 100%; height: 100%; object-fit: cover; border-radius: 8px;"
                                     onerror="this.onerror=null; this.src='/static/img/placeholder.png'; this.style.objectFit='contain';">
                            </div>
                            <div th:if="${not file.image}" class="file-preview">
                                📄
                            </div>
                            <div class="file-details">
                                <div class="file-name" th:text="${file.originalName}"></div>
                                <div class="file-size" th:text="${file.size + ' bytes'}"></div>
                            </div>
                        </div>
                        <div class="file-actions">
                            <button th:if="${file.image}" class="btn btn-view" onclick="viewImage(this)">
                                👁️ 查看
                            </button>
                            <a th:href="'/share/download/' + ${file.id} + '?token=' + ${token}" class="btn btn-download" onclick="downloadFile(this)">
                                ⬇️ 下载
                            </a>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <!-- 图片查看模态框 -->
    <div id="imageModal" class="modal" onclick="closeModal(event)">
        <div class="modal-content">
            <button class="modal-close" onclick="closeModal()">&times;</button>
            <img id="modalImage" class="modal-image" src="" alt="">
        </div>
    </div>

    <script>
        function viewImage(button) {
            const fileItem = button.closest('.file-item');
            const fileName = fileItem.querySelector('.file-name').textContent;
            const fileId = fileItem.querySelector('.btn-download').getAttribute('href').split('/')[3].split('?')[0];
            const token = new URLSearchParams(window.location.search).get('token') || '';

            // 构建查看原图的URL
            const viewUrl = `/share/view/${fileId}?token=${token}`;

            const modal = document.getElementById('imageModal');
            const modalImage = document.getElementById('modalImage');
            const modalContent = modal.querySelector('.modal-content');

            // 添加加载中提示
            const loadingDiv = document.createElement('div');
            loadingDiv.id = 'shareImageLoading';
            loadingDiv.style.cssText = `
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                color: white;
                text-align: center;
                z-index: 1003;
                min-width: 120px;
                white-space: nowrap;
                font-size: 16px;
                font-weight: 500;
                text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
                line-height: 1.5;
                padding: 10px 15px;
                background: rgba(0, 0, 0, 0.6);
                border-radius: 8px;
                backdrop-filter: blur(4px);
            `;
            loadingDiv.textContent = '加载中...';

            // 清理之前的内容
            const existingLoading = document.getElementById('shareImageLoading');
            if (existingLoading) {
                existingLoading.remove();
            }

            // 重置图片显示状态
            modalImage.style.display = 'none';
            modalContent.appendChild(loadingDiv);

            // 设置图片加载事件
            modalImage.onload = function() {
                console.log('分享页面图片加载成功');
                // 移除加载中提示
                loadingDiv.remove();
                // 显示图片
                modalImage.style.display = 'block';
                // 分享页面只查看原图，不生成二维码
            };

            modalImage.onerror = function() {
                console.error('分享页面图片加载失败:', viewUrl);
                loadingDiv.remove();
                // 显示错误提示
                const errorDiv = document.createElement('div');
                errorDiv.id = 'shareImageError';
                errorDiv.style.cssText = loadingDiv.style.cssText;
                errorDiv.textContent = '图片加载失败';
                modalContent.appendChild(errorDiv);
            };

            // 开始加载图片
            modalImage.src = viewUrl;
            modalImage.alt = fileName;
            modal.style.display = 'flex';
        }

        function generateShareQRCode(fileId, token, fileName) {
            // 构建分享链接（包含token）
            const shareUrl = `${window.location.origin}/share/download/${fileId}?token=${token}`;

            // 创建或获取二维码容器
            let qrContainer = document.getElementById('shareQRContainer');
            if (!qrContainer) {
                qrContainer = document.createElement('div');
                qrContainer.id = 'shareQRContainer';
                qrContainer.style.cssText = `
                    position: absolute;
                    bottom: 20px;
                    right: 20px;
                    width: 180px;
                    background: rgba(255, 255, 255, 0.95);
                    border-radius: 12px;
                    padding: 15px;
                    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    gap: 10px;
                    z-index: 1001;
                `;

                const qrInfo = document.createElement('div');
                qrInfo.className = 'qr-info';
                qrInfo.innerHTML = `
                    <p style="margin: 0; font-size: 14px; font-weight: 600; color: #333;">扫描二维码下载照片</p>
                    <p style="margin: 5px 0 0 0; font-size: 12px; color: #666; font-weight: normal;">30分钟有效 · 最多10次下载</p>
                `;

                qrContainer.appendChild(qrInfo);
                document.querySelector('#imageModal .modal-content').appendChild(qrContainer);
            }

            // 显示加载状态
            const qrLoading = document.createElement('div');
            qrLoading.id = 'shareQRLoading';
            qrLoading.className = 'qr-loading';
            qrLoading.textContent = '生成二维码...';
            qrLoading.style.cssText = 'color: #666; font-size: 14px; text-align: center; min-height: 160px; display: flex; align-items: center; justify-content: center;';

            const qrCode = document.createElement('img');
            qrCode.id = 'shareQRCode';
            qrCode.className = 'modal-qr-code';
            qrCode.style.cssText = 'width: 160px; height: 160px; border: 2px solid #f0f0f0; border-radius: 8px; background: white; display: none;';

            // 清理旧的二维码内容
            const oldQRLoading = document.getElementById('shareQRLoading');
            const oldQRCode = document.getElementById('shareQRCode');
            if (oldQRLoading) oldQRLoading.remove();
            if (oldQRCode) oldQRCode.remove();

            qrContainer.appendChild(qrLoading);
            qrContainer.appendChild(qrCode);

            // 生成二维码
            const qrImageUrl = `/share/qrcode/${token}`;
            qrCode.onload = function() {
                qrLoading.style.display = 'none';
                qrCode.style.display = 'block';
            };

            qrCode.onerror = function() {
                qrLoading.style.display = 'none';
                const errorDiv = document.createElement('div');
                errorDiv.className = 'qr-error';
                errorDiv.style.cssText = 'color: #e74c3c; font-size: 12px; text-align: center; min-height: 160px; display: flex; align-items: center; justify-content: center;';
                errorDiv.textContent = '二维码生成失败';
                qrContainer.appendChild(errorDiv);
            };

            qrCode.src = qrImageUrl;
        }

        function closeModal(event) {
            if (!event || event.target.id === 'imageModal' || event.target.className === 'modal-close') {
                const modal = document.getElementById('imageModal');
                modal.style.display = 'none';

                // 清理分享页面添加的元素
                const shareImageLoading = document.getElementById('shareImageLoading');
                const shareImageError = document.getElementById('shareImageError');
                const shareQRContainer = document.getElementById('shareQRContainer');

                if (shareImageLoading) shareImageLoading.remove();
                if (shareImageError) shareImageError.remove();
                if (shareQRContainer) shareQRContainer.remove();
            }
        }

        function downloadFile(link) {
            // 保持原有的默认下载行为，不做任何阻止
            // 浏览器会自动处理 <a> 标签的下载
        }

        function batchDownloadAll() {
            // 使用Thymeleaf传递的token
            const token = '[[${token}]]';
            
            if (!token) {
                alert('下载参数缺失');
                return;
            }
            
            if (confirm('确定要下载全部文件吗？将生成一个压缩包包含所有文件。')) {
                // 请求服务器生成压缩包
                const downloadUrl = `/share/batch-download?token=${token}`;
                
                // 创建隐藏的下载链接
                const a = document.createElement('a');
                a.href = downloadUrl;
                a.style.display = 'none';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                
                // 显示下载提示
                const button = document.querySelector('.btn-batch-download');
                const originalText = button.textContent;
                button.textContent = '正在生成压缩包...';
                button.disabled = true;
                
                // 3秒后恢复按钮状态
                setTimeout(() => {
                    button.textContent = originalText;
                    button.disabled = false;
                }, 3000);
            }
        }

        // ESC键关闭模态框
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeModal();
            }
        });

        // 阻止模态框内容点击时关闭
        document.querySelector('.modal-content').addEventListener('click', function(event) {
            event.stopPropagation();
        });
    </script>
</body>
</html>